import { EventEmitter } from "events";
import { createSocket, RemoteInfo } from 'dgram'
import { parseRTPPacket, RTPPacket } from './RTPPacket'
// import { RTPTransport } from './RTPTransport'
import { RtpPsTransport, PSPacket } from './RtpPsTransport';
import { getVideoInfo, StreamInfo } from "./ParseVideoInfo";

// export abstract class GBClient extends EventEmitter {
export class GBClient extends EventEmitter {
    private psTransport: RtpPsTransport;
    private streamInfo?: StreamInfo = undefined;
    constructor(public readonly rtpVideoPort: number) {
        super();
        this.psTransport = new RtpPsTransport();
        this.init();
    };
    private onPacket(packet: PSPacket): void {
        console.log(packet);
        if (!this.streamInfo && packet.isIDE && packet.streamType) {
            const info = getVideoInfo(packet.streamType, packet.payload);
            console.log("--------------------------------------");
            console.log(info);
            console.log("--------------------------------------");
        }
    }
    private init() {
        this.psTransport.on("packet",this.onPacket);
        this.listenUdpPort();
    }
    private async listenUdpPort() {
        const rtpVideoReceiver = createSocket("udp4");
        rtpVideoReceiver.on("message", (msg: Buffer, rinfo: RemoteInfo) => {
            // console.log("##################################################################");
            const packet = parseRTPPacket(msg);
            // console.log(packet.timestamp);
            // console.log(msg.slice(0, 100).toString('hex'));
            this.transportData(packet);
        });
        await new Promise(resolve => {
            rtpVideoReceiver.bind(this.rtpVideoPort, () => {
                console.log(`start listen udp port: ${this.rtpVideoPort}`);
                resolve();
            });
        });
    }
    private transportData(pakcet: RTPPacket) {
        this.psTransport.onData(pakcet);
    }
}